<template>
  <div class="task-container layout-padding">
    <el-card shadow="hover">
      <div class="mb15 toolbar">
        <el-input
            v-model="state.filter.keyword"
            placeholder="搜索任务标题或描述"
            clearable
            class="mr15"
            style="width: 200px"
            @input="getTableData"
        />
        <el-button size="default" type="primary" @click="onOpenAddTask">发布新任务</el-button>
      </div>

      <el-table :data="state.tableData.data" stripe style="width: 100%" v-loading="state.tableData.loading">
        <el-table-column label="标题" prop="title" min-width="60px"/>
        <el-table-column label="描述" prop="description"/>
        <el-table-column label="任务创建者" prop="assignee_id" min-width="70px">
          <template #default="scope">
            <span>{{ scope.row.creator.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分配学生" prop="assignee_id" min-width="65px">
          <template #default="scope">
            <span>{{ scope.row.assignee.name }}</span>

          </template>
        </el-table-column>
        <el-table-column label="任务类型" min-width="85px">
          <template #header>
            <el-select v-model="state.filter.typeId" placeholder="任务类型" clearable size="small" style="width: 100%">
              <el-option
                  v-for="taskType in state.taskTypes"
                  :key="taskType.id"
                  :label="taskType.name"
                  :value="taskType.id"
              />
            </el-select>
          </template>
          <template #default="scope">
            <el-tag type="primary">{{ scope.row.taskType?.name || '未分类' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="任务文件" min-width="65px">
          <template #default="scope">
            <el-link
                v-if="scope.row.taskfile"
                type="primary"
                @click="downloadFile(scope.row.id, scope.row.taskfile)"
            >
              下载文件
            </el-link>
            <span v-else>无任务文件</span>
          </template>
        </el-table-column>
        <el-table-column label="提交文件" min-width="65px">
          <template #default="scope">
            <el-link
                v-if="scope.row.resultfile"
                type="success"
                @click="downloadFile(scope.row.id, scope.row.resultfile)"
            >
              下载文件
            </el-link>
            <span v-else>未提交</span>
          </template>
        </el-table-column>
        <el-table-column label="任务状态" min-width="85px">
          <template #header>
            <el-select v-model="state.filter.status" placeholder="任务状态" clearable size="small" style="width: 100%">
              <el-option label="未提交" :value="0"/>
              <el-option label="待审核" :value="2"/>
              <el-option label="已通过" :value="3"/>
              <el-option label="未通过" :value="4"/>
            </el-select>
          </template>
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="info">未提交</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 4" type="danger">未通过</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="100px">
          <template #header>
            <el-select v-model="state.filter.order" placeholder="排序方式" size="small" style="width: 100%">
              <el-option label="创建时间降序" value="desc"/>
              <el-option label="创建时间升序" value="asc"/>
            </el-select>
          </template>
          <template #default="scope">
            {{ scope.row.createdAt }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" min-width="100px">
          <template #header>
            <el-select v-model="state.filter.order" placeholder="排序方式" size="small" style="width: 100%">
              <el-option label="更新时间降序" value="desc"/>
              <el-option label="更新时间升序" value="asc"/>
            </el-select>
          </template>
          <template #default="scope">
            {{ scope.row.updatedAt }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="259px">
          <template #default="scope">
            <el-button size="small" type="primary" @click="onOpenEditTask(scope.row)">编辑</el-button>
            <el-button
                v-if="scope.row.status === 2"
                size="small"
                type="success"
                @click="onOpenReviewTask(scope.row)"
            >
              审核
            </el-button>
            <el-button size="small" @click="viewTaskDetail(scope.row)">详情</el-button>
            <el-button size="small" type="danger" @click="onRowDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          size="small"
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :pager-count="5"
          :page-sizes="[10, 20, 30]"
          v-model:current-page="state.tableData.param.page"
          background
          v-model:page-size="state.tableData.param.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>

    <!-- 任务创建/编辑对话框 -->
    <TaskDialog ref="taskDialogRef" @refresh="getTableData()"/>

    <!-- 任务审核对话框 -->
    <TaskReviewDialog ref="taskReviewDialogRef" @refresh="getTableData()"/>

    <!-- 任务详情对话框 -->
    <TaskDetailDialog ref="taskDetailDialogRef"/>
  </div>
</template>

<script setup lang="ts" name="teacherTask">
import {defineAsyncComponent, reactive, onMounted, ref, computed, watch} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
import {getTaskList, deleteTask, downloadTaskFile, getTaskDetail, getTaskTypes} from "/@/views/task/task.ts";
import Axios from "/@/utils/Axios";

// 引入组件
const TaskDialog = defineAsyncComponent(() => import("./TaskDialog.vue"));
const TaskReviewDialog = defineAsyncComponent(() => import("./TaskReviewDialog.vue"));
const TaskDetailDialog = defineAsyncComponent(() => import("./TaskDetailDialog.vue"));

// 定义变量内容
const taskDialogRef = ref();
const taskReviewDialogRef = ref();
const taskDetailDialogRef = ref();

const state = reactive({
  users: [],
  taskTypes: [],
  filter: {
    status: null,
    order: "desc",
    keyword: "",
    typeId: null
  },
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      page: 1,
      limit: 10
    }
  }
});


// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  getTaskList({
    page: state.tableData.param.page,
    limit: state.tableData.param.limit,
    order: state.filter.order,
    status: state.filter.status,
    keyword: state.filter.keyword,
    typeId: state.filter.typeId
  }).then((res) => {
    console.log(res);
    if (res.tasks) {
      state.tableData.data = res.tasks;
      state.tableData.total = res.total_count;
    } else {
      ElMessage.error(res.message || "获取任务列表失败");
    }
    state.tableData.loading = false;
  }).catch((err) => {
    state.tableData.loading = false;
    ElMessage.error(err.message || "获取任务列表失败");
  });
};

// 打开新增任务弹窗
const onOpenAddTask = () => {
  taskDialogRef.value.openDialog("add", null, state.users,state.taskTypes);
};

// 打开修改任务弹窗
const onOpenEditTask = (row) => {
  taskDialogRef.value.openDialog("edit", row, state.users, state.taskTypes);
};

// 打开审核任务弹窗
const onOpenReviewTask = (row) => {
  taskReviewDialogRef.value.openDialog(row);
};

// 查看任务详情
const viewTaskDetail = (row) => {
  taskDetailDialogRef.value.openDialog(row.id);
};

// 删除任务
const onRowDel = (row) => {
  ElMessageBox.confirm(`此操作将删除任务"${row.title}"，是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
      .then(() => {
        deleteTask(row.id).then((res) => {
          if (res.success === 1) {
            ElMessage.success("删除成功");
            getTableData();
          } else {
            ElMessage.error(res.message || "删除失败");
          }
        }).catch(err => {
          ElMessage.error(err.message || "删除失败");
        });
      })
      .catch(() => {
      });
};

// 下载文件
const downloadFile = (taskId,fileName) => {
  // 下载文件
    downloadTaskFile(taskId).then((response) => {

      // 使用正则表达式提取文件名
      const filename = fileName.match(/[^/]+$/)[0];

      const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
};

// 分页大小改变
const onHandleSizeChange = (val) => {
  state.tableData.param.limit = val;
  getTableData();
};

// 当前页改变
const onHandleCurrentChange = (val) => {
  state.tableData.param.page = val;
  getTableData();
};

// 监听筛选条件变化
watch(() => [state.filter.status, state.filter.order, state.filter.typeId], () => {
  getTableData();
}, {deep: true});

// 页面加载时
onMounted(() => {
  // 获取所有用户
  Axios.get("/backapi/users").then((res) => {
    state.users = res.data.allUser;
  }).catch(() => {
    ElMessage.error("获取用户列表失败");
  });

  // 获取任务类型列表
  getTaskTypes().then((res) => {
    state.taskTypes = res.taskTypes || [];
  })
  // 获取任务列表
  getTableData();
});
</script>

<style scoped lang="scss">
.task-container {
  padding: 0px;

  .toolbar {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 15px;
  }

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }
  }
}
</style>
